#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __init__ import  FConfig
from common import run
from subprocess import Popen,PIPE
import os,re,signal,datetime


SCRIPT = os.path.join(FConfig.DATADIR,"fricorder_record.sh")

def getQualite():
    return ["direct","OGM"]

def getJours(date,nb=7):
    l=[]
    for i in range(nb):
        l.append( (i,date+datetime.timedelta(days=i)))
    return l


def getAtList():
    l=[]
    buf=run(["atq"])
    if buf:
        for i in buf.split("\n"):
            t=i.strip().split("\t")
            code,date = t[0],t[1][:16]

            b=run(["at","-c",str(code)])
            if SCRIPT in b:
                chaine,debut,duree = FileId.unmake(b)
                l.append( (code,chaine,debut,duree) )
    return l

def delAt(code):
    run(["atrm",str(code)])

def isAtdRunning():
    return os.path.isfile("/var/run/atd.pid")

def runAt(stream,chaine,quality,datet,duree,destination):
    fin= datet+datetime.timedelta(minutes=duree)
    now = datetime.datetime.now()

    if now >= fin:
        err="On ne peut pas enregistrer dans le passé ;-)"
    else:
        if now > datet:
            # on va tenter de rattrapper le coup
            datet = now
            duree = ((fin-now).seconds/60) +1

        name = FileId.make(chaine,datet,duree)
        file = os.path.join(destination,name)

        cmd_echo=["echo",
            SCRIPT,
            '"%s"'%stream,
            str(duree*60),  # convert en secondes !!!!
            quality.lower(),    #convert en minuscule
            '"%s"'%file,
            ]

        cmd_at=[
            "at",
            datet.strftime("%H:%M %d.%m.%y")
            ]

        # `echo xxxx | at xxx`
        p1 = Popen(cmd_echo, stdout=PIPE)
        p2 = Popen(cmd_at, stdin=p1.stdout, stdout=PIPE)
        #~ print cmd_echo,cmd_at
        print p2.communicate()[0]
        err=""

    return err

class FileId:
    """
    pour la constitution et la deconstitution du nom de fichier
    servant a stocker des infos
    """
    @staticmethod
    def make(chaine,datet,duree):
        debut = datet.strftime("%Y-%m-%d_%H-%M")
        return "[%s][%s][%d]" % (chaine,debut,duree)

    @staticmethod
    def unmake(chaine):
        r=re.compile(r"\[([^\]]+)\]\[(\d+)-(\d+)-(\d+)_(\d+)-(\d+)\]\[([^\]]+)\]")
        g=r.search(chaine)
        if g:
            try:
                chaine=g.group(1)
                datet=datetime.datetime(
                    int(g.group(2)),
                    int(g.group(3)),
                    int(g.group(4)),
                    int(g.group(5)),
                    int(g.group(6))
                    )
                duree=int(g.group(7))
                return chaine,datet,duree
            except:
                print "FileId.unmake() : prob dans la deconstitution de ",chaine

    @staticmethod
    def genPidFileName(fileid):
        return os.path.join(FConfig.CACHEDIR, fileid+".pid")

    @staticmethod
    def genHaltFileName(fileid):
        return os.path.join(FConfig.CACHEDIR, fileid+".halt")

    @staticmethod
    def toggleHaltFileName(fileid):
        file= FileId.genHaltFileName(fileid)
        if FileId.isHaltFileName(fileid):
            os.unlink(file)
        else:
            open(file,"w").write("")

    @staticmethod
    def isHaltFileName(fileid):
        file= FileId.genHaltFileName(fileid)
        return os.path.isfile(file)


def cancelJob(job,fileid):
    print "Cancel job",job
    delAt(job)

    # s'occupe du "halt" file
    if FileId.isHaltFileName(fileid):
        FileId.toggleHaltFileName(fileid)

    # tente de voir si c un "en cours", pour tuer vlc et scripts
    # fileid+pid
    file=FileId.genPidFileName(fileid)
    if os.path.isfile(file):
        # le fichier "pid" existe (c donc que vlc tourne)
        for pid in open(file):
            # on tue tous les pid du fichier
            os.kill(int(pid),signal.SIGKILL)
        print "kill vlc for",file
        os.unlink(file)


if __name__ == "__main__":
    date=datetime.datetime.now()+datetime.timedelta(days=5)
    print getQualite()
    print getJours(date,14)
    print getAtList()
    print isAtdRunning()
    print runAt("rtsp://mafreebox.freebox.fr/fbxtv_pub/stream?namespace=1&service=201&flavour=sd","toto","direct",date,100,os.environ['HOME'])
    #~ delAt(44)
